package com.example.video.common.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;

public class XmlUtils {
    private static final String DEFAULT_XML_VERSION = "1.0";
    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * 从XML字符串中提取指定标签的值。
     *
     * @param xmlString XML字符串
     * @param tagName 标签名
     * @return 标签的值
     * @throws IllegalArgumentException 如果XML字符串为空或标签不存在
     */
    public static String getValueFromTag(String xmlString, String tagName) {
        if (xmlString == null || xmlString.trim().isEmpty()) {
            throw new IllegalArgumentException("XML string is empty or null.");
        }

        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xmlString));
            Document doc = dBuilder.parse(is);

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.compile("//" + tagName).evaluate(doc, XPathConstants.NODESET);

            if (nodeList.getLength() > 0) {
                Node node = nodeList.item(0);
                return node.getTextContent();
            } else {
                throw new IllegalArgumentException("Tag not found: " + tagName);
            }

        } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
            throw new RuntimeException("Error parsing XML or evaluating XPath expression.", e);
        }
    }


    public static void main(String[] args) {
        String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<LPListAuditSearchResult version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\n" +
                "    <searchID>0</searchID>\n" +
                "    <responseStatus>true</responseStatus>\n" +
                "    <responseStatusStrg>OK</responseStatusStrg>\n" +
                "    <LicensePlateInfoList>\n" +
                "        <numOfMatches>0</numOfMatches>\n" +
                "        <totalMatches>0</totalMatches>\n" +
                "        <searchResultPosition>0</searchResultPosition>\n" +
                "        <maxResults>1</maxResults>\n" +
                "    </LicensePlateInfoList>\n" +
                "</LPListAuditSearchResult>";

        try {
            String searchID = XmlUtils.getValueFromTag(xmlString, "numOfMatches");
            System.out.println("searchID: " + searchID);

            String responseStatusStrg = XmlUtils.getValueFromTag(xmlString, "responseStatusStrg");
            System.out.println("responseStatusStrg: " + responseStatusStrg);

            // 尝试获取不存在的标签
            String nonExistentTag = XmlUtils.getValueFromTag(xmlString, "nonExistentTag");
            System.out.println("nonExistentTag: " + nonExistentTag);

        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
        }
    }
}
